package com.uchengwang.ui.cm_ui.rychat.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.uchengwang.R;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.cm_ui.rychat.bean.BigEmojicon;
import com.uchengwang.ui.cm_ui.rychat.utils.BigEmojiconData;
import com.uchengwang.ui.cm_ui.rychat.msgtype.BigEmoMessage;

import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imkit.emoticon.IEmojiItemClickListener;
import io.rong.imkit.emoticon.IEmoticonTab;
import io.rong.imkit.utilities.ExtensionHistoryUtil;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

/**
 * Created by U城网 on 2017/10/20.
 */

public class BigEmotionTab implements IEmoticonTab {

    private LayoutInflater mLayoutInflater;
    private LinearLayout mIndicator;
    private int selected = 0;
    private String mUserId;//自己的ID
    private IEmojiItemClickListener mOnItemClickListener;
    private int mEmojiCountPerPage = 10;
    private Context context;
    private String mTargetId;//消息接受者的ID
    private Conversation.ConversationType type;
    /**
     * 表情数据
     */
    private List<BigEmojicon> emoList ;

    public BigEmotionTab(String mTargetId, Conversation.ConversationType type){
        this.mTargetId = mTargetId;
        this.type = type;
    }
    
    @Override
    public Drawable obtainTabDrawable(Context context) {
        return context.getResources().getDrawable(R.drawable.icon_big_tab);
    }

    @Override
    public View obtainTabPager(Context context) {
        this.context = context;
        this.mUserId = RongIMClient.getInstance().getCurrentUserId();
        return this.initView(context);
    }

    @Override
    public void onTableSelected(int i) {

    }

    private View initView(final Context context) {
        emoList = BigEmojiconData.getData().getEmojiconList();
        int count = emoList.size();

//        try {
//            this.mEmojiCountPerPage = context.getResources().getInteger(context.getResources().getIdentifier("rc_extension_emoji_count_per_page", "integer", context.getPackageName()));
//        } catch (Exception var7) {
//            this.mEmojiCountPerPage = 10;
//        }

        int pages = count / this.mEmojiCountPerPage + (count % this.mEmojiCountPerPage != 0?1:0);
        View view = LayoutInflater.from(context).inflate(R.layout.rc_ext_emoji_pager, (ViewGroup)null);
        ViewPager viewPager = (ViewPager)view.findViewById(R.id.rc_view_pager);
        this.mIndicator = (LinearLayout)view.findViewById(R.id.rc_indicator);
        this.mLayoutInflater = LayoutInflater.from(context);
        viewPager.setAdapter(new EmojiPagerAdapter(pages));
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            public void onPageSelected(int position) {
//                ExtensionHistoryUtil.setEmojiPosition(context, mUserId, position);
//                onIndicatorChanged(selected, position);
//                selected = position;
            }

            public void onPageScrollStateChanged(int state) {
            }
        });
        viewPager.setOffscreenPageLimit(1);
        this.initIndicator(pages, this.mIndicator);
        int position = ExtensionHistoryUtil.getEmojiPosition(context, this.mUserId);
        viewPager.setCurrentItem(position);
        this.onIndicatorChanged(-1, position);
        return view;
    }

    private void initIndicator(int pages, LinearLayout indicator) {
        for(int i = 0; i < pages; ++i) {
            ImageView imageView = (ImageView)this.mLayoutInflater.inflate(R.layout.rc_ext_indicator, (ViewGroup)null);
            imageView.setImageResource(R.drawable.rc_ext_indicator);
            indicator.addView(imageView);
        }

    }

    private void onIndicatorChanged(int pre, int cur) {
        int count = this.mIndicator.getChildCount();
        if(count > 0 && pre < count && cur < count) {
            ImageView curView;
            if(pre >= 0) {
                curView = (ImageView)this.mIndicator.getChildAt(pre);
                curView.setImageResource(R.drawable.rc_ext_indicator);
            }

            if(cur >= 0) {
                curView = (ImageView)this.mIndicator.getChildAt(cur);
                curView.setImageResource(R.drawable.rc_ext_indicator_hover);
            }
        }

    }

    private class ViewHolder {
        ImageView emojiIV;
        TextView emojiTV;

        private ViewHolder() {
        }
    }

    private class EmojiAdapter extends BaseAdapter {
        int count;
        int index;

        public EmojiAdapter(int index, int count) {
            this.count = Math.min(mEmojiCountPerPage, count - index);
            this.index = index;
        }

        public int getCount() {
            return this.count;
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0L;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if(convertView == null) {
                viewHolder = new ViewHolder();
                convertView = mLayoutInflater.inflate(R.layout.ease_row_big_expression, (ViewGroup)null);
                viewHolder.emojiIV = (ImageView)convertView.findViewById(R.id.iv_expression);
                viewHolder.emojiTV = (TextView) convertView.findViewById(R.id.tv_name);
                convertView.setTag(viewHolder);
            }

            viewHolder = (ViewHolder)convertView.getTag();

            BigEmojicon emojicon = emoList.get(position);
            ImageManager.getInstance().loadImage(context, viewHolder.emojiIV, emojicon.getIcon(), ImageManager.ImageType.NARMOL);

            return convertView;
        }
    }

    private class EmojiPagerAdapter extends PagerAdapter {
        int count;

        public EmojiPagerAdapter(int count) {
            this.count = count;
        }

        public Object instantiateItem(ViewGroup container, int position) {
            View view = mLayoutInflater.inflate(R.layout.ease_expression_gridview, (ViewGroup)null);
            GridView gridView = (GridView)view.findViewById(R.id.gridview);
            gridView.setAdapter(new EmojiAdapter(position * mEmojiCountPerPage, emoList.size()));
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //发送消息 已文本信息发出去
                    BigEmojicon emojicon = emoList.get(position);
                    BigEmoMessage bigEmoMessage =  new BigEmoMessage();
                    bigEmoMessage.setBigName(emojicon.getName());
                    bigEmoMessage.setBigCodeId(emojicon.getIdentityCode());

                    Message myMessage = Message.obtain(mTargetId, type, bigEmoMessage);

                    RongIM.getInstance().sendMessage(myMessage, null, null, new IRongCallback.ISendMessageCallback() {
                        @Override
                        public void onAttached(Message message) {
                            Log.d("ryjjf", "信息发送成功onAttached");
                        }

                        @Override
                        public void onSuccess(Message message) {
                            Log.d("ryjjf", "信息发送成功");
                        }

                        @Override
                        public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                            int code = errorCode.getValue();
                            String msg = errorCode.getMessage();
                            Log.d("ryjjf", "信息发送失败=code="+code+"=msg="+msg);

                        }
                    });
                }
            });
            container.addView(gridView);
            return gridView;
        }

        public int getItemPosition(Object object) {
            return -2;
        }

        public int getCount() {
            return this.count;
        }

        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            View layout = (View)object;
            container.removeView(layout);
        }
    }
}
